package com.easyattendance.services;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.EmailSettings;
import com.easyattendance.util.HibernateUtil;

public class EmailService {
	
	/* Method to CREATE a mail setting in the database */
	   public synchronized boolean addEmailSetting(EmailSettings emailSetting){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();
	         session.save(emailSetting); 
	         
	         tx.commit();
	         result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	     return result;
}


public boolean ifMailSettingAlreadyExists(String emailId) {
	 boolean flag = false;
	 
	 Session session = HibernateUtil.openSession();
     Transaction tx = null;
     List mail_settings = null;
     try{
        tx = session.beginTransaction();
        mail_settings = session.createQuery("FROM EmailSettings").list(); 
        for (Iterator iterator = mail_settings.iterator(); iterator.hasNext();){
       	 EmailSettings tempmail = (EmailSettings) iterator.next(); 
           if(tempmail.getSend_email_id().equals(emailId))
           {
           	  System.out.println("Email setting already exists for this section");
           	  flag = true;
           	 break;
           }
            
        }
        tx.commit();
     }catch (HibernateException e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace(); 
     }finally {
        session.close(); 
     }
     return flag;
  }   


}